<template>
  <div class="plan-review bg-background text-foreground p-4">
    <h2 class="text-2xl font-bold mb-4">预案评审</h2>

    <!-- Search Bar -->
    <div class="bg-card text-card-foreground p-4 mb-4 rounded shadow">
      <QueryForm :model="search" :formItems="formItems" @search="searchPlans" @reset="resetSearch" />
    </div>

    <!-- Action Buttons -->
    <div class="mb-4 space-x-2">
      <el-button type="primary" @click="openAddDialog">录入</el-button>
      <el-button type="danger" @click="deleteSelected">删除</el-button>
      <el-button @click="openImportDialog">导入</el-button>
      <el-button @click="exportData(planData, '预案评审', selectedIds)">导出</el-button>
    </div>
    <!-- Data Table -->
    <div class="bg-card text-card-foreground my-6 rounded shadow-md">
      <el-table v-loading="loading" :data="displayedPlanData" @selection-change="handleSelectionChange"
        style="width: 100%" ref="table" align="center" class="data-table" :header-cell-style="headerCellStyle"
        :row-key="rowKey">
        <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
        <el-table-column prop="EMERGENCE_PLAN_ID" label="预案编码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="PARK_CODE" label="园区编码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="COMPANY_CODE" label="企业编码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="AREA_CODE" label="行政区划" header-align="center" align="center"></el-table-column>
        <el-table-column prop="PREPARATION_DEPARTMENT" label="编制单位" header-align="center"
          align="center"></el-table-column>
        <el-table-column prop="EMERGENCE_PLAN_NAME" label="预案名称" header-align="center" align="center"></el-table-column>
        <el-table-column prop="EMERGENCE_PLAN_TYPE" label="预案类别" header-align="center" align="center"></el-table-column>
        <el-table-column prop="EMERGENCE_PLAN_LEVEL" label="预案等级" header-align="center" align="center"></el-table-column>
        <el-table-column prop="Review_Status" label="状态" header-align="center" align="center">
          <template #default="scope">


            <el-text class="mx-1" style="color: #006400;" v-if="scope.row.Review_Status == '已备案'">{{
              scope.row.Review_Status }}</el-text>
            <el-text class="mx-1" v-else :type="textstat(scope.row.Review_Status)">{{ scope.row.Review_Status }}</el-text>
          </template>
        </el-table-column>
        <el-table-column label="操作" header-align="center" align="center">
          <template #default="scope">
            <el-button
              v-if="scope.row.Review_Status == '待备案' || scope.row.Review_Status == '待公布' || scope.row.Review_Status == '已备案'"
              type="primary" size="small" @click="reviewPlan(scope.row, '详情')" link>详情</el-button>
            <el-button v-if="scope.row.Review_Status == '待备案'" type="warning" size="small" @click="viewDetails(scope.row)"
              link>备案</el-button>
            <el-button v-if="scope.row.Review_Status == '待公布'" type="warning" size="small"
              @click="reviewPlan(scope.row, '待公布')" link>公布</el-button>
            <el-button v-if="scope.row.Review_Status == '待审批'" type="primary" size="small"
              @click="reviewPlan(scope.row, '待审批')" link>审批</el-button>
            <el-button v-if="scope.row.Review_Status == '待评审'" type="primary" size="small"
              @click="reviewPlan(scope.row, '待评审')" link>评审</el-button>
            <el-button v-if="scope.row.Review_Status == '待评审'" type="primary" size="small"
              @click="openEditDialog(scope.row)" link>编辑</el-button>

          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- Pagination -->
    <Pagination v-if="planData.length" :tableData="planData" @alltabledata="alltabledata" />
    <!-- 新增申请 -->
    <el-dialog width="600px" class="dialog-from" v-model="isAddDialogOpen" :title="isEditing ? '编辑评审' : '新增评审'"
      destroy-on-close align-center :before-close="closeAddDialog">
      <form>
        <!-- 基本信息 -->
        <div>
          <div class="tablename">
            <div
              style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
            </div>
            <span>基本信息</span>
          </div>
          <div class="grid grid-cols-3 gap-6">
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">预案编码：</label>
              <el-input type="text" v-model="newRecord.EMERGENCE_PLAN_ID" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">园区编码：</label>
              <el-input type="text" v-model="newRecord.PARK_CODE" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">企业编码：</label>
              <el-input type="text" v-model="newRecord.COMPANY_CODE" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">行政区划：</label>
              <el-select v-model="newRecord.AREA_CODE" placeholder="请选择" clearable>
                <el-option label="大荔县" value="大荔县" />
              </el-select>
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">编制单位：</label>
              <el-input type="text" v-model="newRecord.PREPARATION_DEPARTMENT" />
            </div>
            <!--  -->
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">预案名称：</label>
              <el-input type="text" v-model="newRecord.EMERGENCE_PLAN_NAME" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">预案类别：</label>
              <el-select v-model="newRecord.EMERGENCE_PLAN_TYPE" placeholder="请选择" clearable>
                <el-option label="综合应急预案" value="综合应急预案" />
                <el-option label="专项应急预案" value="专项应急预案" />
                <el-option label="现场处置方案" value="现场处置方案" />
                <el-option label="特殊时期/重大活动应急预案" value="特殊时期/重大活动应急预案" />
              </el-select>
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">预案等级：</label>
              <el-select v-model="newRecord.EMERGENCE_PLAN_LEVEL" placeholder="请选择" clearable>
                <el-option label="上级应急预案" value="上级应急预案" />
                <el-option label="园区级应急预案" value="园区级应急预案" />
                <el-option label="企业级应急预案" value="企业级应急预案" />
              </el-select>
            </div>

            <!--  -->
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">风险是否告知周边单位：</label>
              <el-select v-model="newRecord.RISK_HAS_TOLD_YES_OR_NO" placeholder="请选择" clearable>
                <el-option label="是" value="1" />
                <el-option label="否" value="0" />
              </el-select>
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">风险告知周边的其他单位资料：</label>
              <!-- <el-input type="text" v-model="newRecord.RISK_HAS_TOLD_YES_OR_NO" /> -->
              <div v-if="isEditing" style="margin:10px 0">
                <div>
                  {{ newRecord.RISK_HAS_TOLD_MATERIAL }}
                </div>
                <el-button style="width: 75px; height: 30px;"
                  @click="uploadfile(apiBaseUrl + '/download/' + newRecord.RISK_HAS_TOLD_MATERIAL)">
                  下载查看

                </el-button>
              </div>

              <input type="file" id="importFile" @change="handleRISK_HAS" accept=".csv, .xlsx" class="mt-1 block w-full">
            </div>
            <!--  -->
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">预案文件：</label>
              <!-- <el-input type="text" v-model="newRecord.PLAN_FILE" required /> -->
              <div v-if="isEditing" style="margin:10px 0">
                <div>
                  {{ newRecord.PLAN_FILE }}
                </div>
                <el-button style="width: 75px; height: 30px;"
                  @click="uploadfile(apiBaseUrl + '/download/' + newRecord.PLAN_FILE)">
                  下载查看
                </el-button>
              </div>
              <input type="file" id="importFile" @change="handlePLANFILE" accept=".csv, .xlsx" class="mt-1 block w-full">
            </div>
          </div>
        </div>
        <hr style="margin:8px" />
        <div class="mt-6 flex justify-end space-x-2">
          <el-button type="primary" @click="addNewPlan" style="width: 75px; height: 30px;">确认</el-button>
          <el-button @click="closeAddDialog" style="width: 75px; height: 30px;">取消</el-button>

        </div>
      </form>
    </el-dialog>
    <!-- 预案评审 预案审批 预案公布 预案详情 -->
    <el-dialog width="800px" class="dialog-from" v-model="isReviewDialogOpen"
      :title="isApproval == '待评审' ? '预案评审' : isApproval == '待审批' ? '预案审批' : isApproval == '待公布' ? '预案公布' : '预案详情'"
      destroy-on-close align-center :before-close="closeReviewDialog">
      <form>
        <div class="tablename">
          <div
            style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
          </div>
          <span>基本信息</span>
        </div>
        <div class="grid grid-cols-3 gap-4">
          <div><strong>预案编码：</strong>{{ selectedItem.EMERGENCE_PLAN_ID }}</div>
          <div><strong>园区编码：</strong>{{ selectedItem.PARK_CODE }}</div>
          <div><strong>企业编码：</strong>{{ selectedItem.COMPANY_CODE }}</div>

          <div><strong>行政区划：</strong>{{ selectedItem.AREA_CODE }}</div>
          <div><strong>编制单位：</strong>{{ selectedItem.PREPARATION_DEPARTMENT }}</div>
          <div><strong>预案名称：</strong>{{ selectedItem.EMERGENCE_PLAN_NAME }}</div>

          <div><strong>预案类别：</strong>{{ selectedItem.EMERGENCE_PLAN_TYPE }}</div>
          <div><strong>预案等级：</strong>{{ selectedItem.EMERGENCE_PLAN_LEVEL }}</div>
          <div><strong>风险是否告知周边单位：</strong>{{ selectedItem.RISK_HAS_TOLD_YES_OR_NO }}
          </div>

          <div><strong>风险告知周边单位文件：</strong>{{ selectedItem.RISK_HAS_TOLD_MATERIAL }}
            <el-button v-if="selectedItem.RISK_HAS_TOLD_MATERIAL != ''" style="width: 75px; height: 30px;"
              @click="uploadfile(apiBaseUrl + '/download/' + selectedItem.RISK_HAS_TOLD_MATERIAL)">
              下载查看
            </el-button>

          </div>
          <div><strong>预案文件：</strong>{{ selectedItem.PLAN_FILE }}

            <el-button v-if="selectedItem.PLAN_FILE != ''" style="width: 75px; height: 30px;"
              @click="uploadfile(apiBaseUrl + '/download/' + selectedItem.PLAN_FILE)">
              下载查看
            </el-button>
          </div>


        </div>
        <div v-show="reviewnameData.length" class="tablename">
          <div
            style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
          </div>
          <span>评审信息</span>
        </div>
        <!-- 评审  -->
        <div v-if="isApproval == '待评审'">
          <div class="grid grid-cols-2 gap-4">
            <div>
              <div>
                <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">评审专家:</label>
                <el-select v-model="reservationreviewForm.Reviewer_NAME" class="set-select" placeholder="请选择">
                  <el-option label="张三" value="张三" />
                </el-select>
              </div>
            </div>
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">评审人员职务:</label>
              <el-select v-model="reservationreviewForm.Reviewer_TYPE" class="set-select" placeholder="请选择">
                <el-option label="组长" value="组长" />
                <el-option label="组员" value="组员" />
              </el-select>
            </div>
          </div>
          <div>
            <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">评审意见：</label>
            <el-input type="text" v-model="reservationreviewForm.Reviewer_RESULT" />
          </div>
        </div>
        <!--审批  -->
        <div v-if="isApproval == '待审批' || isApproval == '待公布' || isApproval == '详情'">
          <div v-for="reirem in reviewnameData" :key="reirem" v-show="reviewnameData.length">
            <div class="grid grid-cols-2 gap-4" style="margin: 10px 0;">
              <div><strong>审核人：</strong>{{ reirem.Reviewer_NAME }}</div>
              <div><strong>审核职务：</strong>{{ reirem.Reviewer_TYPE }}</div>
            </div>
            <div>
              <strong>评审意见：</strong>
              <span> {{ reirem.Reviewer_RESULT }}</span>
            </div>
          </div>
          <!-- 审批意见 -->
          <div>
            <div class="tablename">
              <div
                style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
              </div>
              <span>审批信息</span>
            </div>
            <div>
              <div v-if="isApproval != '待审批'">
                <div style="margin:10px 0"><strong>审批人：</strong>{{ selectedItem.Approve_Staff }}</div>
                <div><strong>审批意见：</strong>{{ selectedItem.Approve_Comment }}</div>
              </div>
              <div v-else>
                <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">审批意见：</label>
                <el-input type="text" v-model="approvafrom.Approve_Comment" />
              </div>
            </div>
          </div>
        </div>
        <div class="mt-6 flex justify-end space-x-2" v-if="isApproval != '详情'">
          <!-- <el-button type="primary" @click="addNewPlan" style="width: 75px; height: 30px;">确认</el-button>
          <el-button type="primary" @click="addNewPlan" style="width: 75px; height: 30px;">确认</el-button> -->
          <div v-if="isApproval == '待评审' || isApproval == '待审批'">
            <el-button type="primary" v-if="isApproval == '待评审'" @click="submitReview('待审批')"
              style="width: 75px; height: 30px;">同意</el-button>
            <el-button type="primary" v-if="isApproval == '待审批'" @click="submitReview('待公布')"
              style="width: 75px; height: 30px;">同意</el-button>
            <el-button type="danger" @click="submitReview('待评审')" style="width: 75px; height: 30px;">驳回</el-button>
          </div>

          <div v-if="isApproval == '待公布'">
            <el-button type="primary" @click="subpublish('待备案')" style="width: 75px; height: 30px;">公布</el-button>
            <el-button type="danger" @click="subpublish('待审批')" style="width: 75px; height: 30px;">驳回公布</el-button>
          </div>
          <el-button @click="closeReviewDialog" style="width: 75px; height: 30px;">取消</el-button>
        </div>
      </form>
    </el-dialog>
    <!-- 备案 -->
    <el-dialog width="600px" class="dialog-from" v-model="isViewDialogOpen" title="预案备案" destroy-on-close align-center
      :before-close="closeViewDialog">
      <form>
        <!-- 基本信息 -->
        <div>
          <div class="grid grid-cols-3 gap-8">
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">单位名称：</label>
              <el-input type="text" v-model="recordData.PREPARATION_DEPARTMENT" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">机构代码：</label>
              <el-input type="text" v-model="recordData.DEPARTMENT_CODE" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">法定代表人：</label>
              <el-input type="text" v-model="recordData.DEPARTMENT_REP" required />
            </div>
            <!--  -->
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">联系电话：</label>
              <el-input type="text" v-model="recordData.DEPARTMENT_REP_PHONE" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">联系人：</label>
              <el-input type="text" v-model="recordData.DEPARTMENT_PER" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">联系电话：</label>
              <el-input type="text" v-model="recordData.DEPARTMENT_PER_PHONE" required />
            </div>
            <!--  -->
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">传真：</label>
              <el-input type="text" v-model="recordData.DEPARTMENT_FAX" />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">电子邮箱：</label>
              <el-input type="text" v-model="recordData.DEPARTMENT_E_MAIL" />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">地址：</label>
              <el-input type="text" v-model="recordData.DEPARTMENT_ADDR" required />
            </div>
            <!--  -->
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">预案名称：</label>
              <el-input type="text" v-model="recordData.EMERGENCE_PLAN_NAME" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">风险级别：</label>
              <el-input type="text" v-model="recordData.PLAN_FILE1" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">报送单位：</label>
              <el-input type="text" v-model="recordData.SUBMIT_DEPARTMENT" required />
            </div>
            <!--  -->
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">备案部门：</label>
              <el-input type="text" v-model="recordData.RECORD_DEPART" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">备案部门性质：</label>
              <el-select v-model="recordData.RECORD_DEPART_NATURE" placeholder="请选择" clearable>
                <el-option label="应急" value="应急" />
                <el-option label="交通运输" value="交通运输" />
                <el-option label="其他" value="其他" />
              </el-select>
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">备案编号：</label>
              <el-input type="text" v-model="recordData.RECORD_CODE" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">报送时间：</label>
              <el-input type="date" v-model="recordData.SUBMIT_TIME" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">预案备案登记资料：</label>
              <!-- <el-input type="text" v-model="recordData.PLAN_TO_RECORD_MATERIAL" required /> -->
              <input type="file" id="importFile" @change="handlePLAN_TO" accept=".csv, .xlsx" class="mt-1 block w-full">
            </div>
          </div>
          <div>
            <label for="staffCode" class="block text-sm font-medium text-muted-foreground">突发环境事件应急预案备案目录：</label>
            <el-input type="text" v-model="recordData.RECORD_CONTENTS" required />
          </div>
          <div>
            <label for="staffCode" class="block text-sm font-medium text-muted-foreground">备案意见：</label>
            <el-input type="text" v-model="recordData.RECORD_COMMENTS" required />
          </div>
        </div>
        <hr style="margin:8px" />
        <div class="mt-6 flex justify-end space-x-2">
          <el-button type="primary" @click="addrecordData" style="width: 75px; height: 30px;">确认</el-button>
          <el-button @click="closeViewDialog" style="width: 75px; height: 30px;">取消</el-button>
        </div>
      </form>
    </el-dialog>
    <!--  -->
    <el-dialog width="400px" class="dialog-from" v-model="isImportDialogOpen" title="导入" destroy-on-close align-center
      :before-close="closeImportDialog">
      <div class="mb-4">
        <label for="importFile" class="block text-sm font-medium">选择文件</label>
        <input type="file" id="importFile" @change="handleFileUpload" accept=".csv, .xlsx" class="mt-1 block w-full">
      </div>
      <div class="mt-4 flex justify-end space-x-2">
        <el-button @click="closeImportDialog"
          class="bg-secondary text-secondary-foreground px-4 py-2 rounded">取消</el-button>
        <el-button v-loading.fullscreen.lock="fullscreenLoading" @click="confirmImport"
          class="bg-accent text-accent-foreground px-4 py-2 rounded" type="primary">确认导入</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance } from 'vue'
import axios from 'axios'
const { proxy } = getCurrentInstance()
import { exportData, uploadfile, checkval } from '#/utils/exportfile.js'
import { dayjs } from "element-plus"
const apiBaseUrl = ref(proxy.$currentUrl + '/api/plan-review')

// 搜索相关
const search = ref({
  EMERGENCE_PLAN_ID: "",
  EMERGENCE_PLAN_TYPE: '',
  EMERGENCE_PLAN_LEVEL: '',
  EMERGENCE_PLAN_NAME: '',
  Review_Status: ''
})
const formItems = ref([
  {
    label: '预案编码：:',
    model: 'EMERGENCE_PLAN_ID',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '预案名称：',
    model: 'EMERGENCE_PLAN_NAME',
    type: 'input',
    // placeholder: '请选择',
    // options: [
    //   { label: '自然灾害', value: '自然灾害' },
    //   { label: '事故灾难', value: '事故灾难' },
    //   { label: '公共卫生时间', value: '公共卫生时间' },
    //   { label: '社会安全事件', value: '社会安全事件' },
    //   { label: '其他突发事件', value: '其他突发事件' },
    // ],
  },
  {
    label: '预案类别：',
    model: 'EMERGENCE_PLAN_TYPE',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '综合应急预案', value: '综合应急预案' },
      { label: '专项应急预案', value: '专项应急预案' },
      { label: '现场处置方案', value: '现场处置方案' },
      { label: '特殊时期/重大活动应急预案', value: '特殊时期/重大活动应急预案' },
    ],
  },
  {
    label: '预案等级：',
    model: 'EMERGENCE_PLAN_LEVEL',
    type: 'select',
    placeholder: '请选择',
    options: [

      { label: '上级应急预案', value: '上级应急预案' },
      { label: '园区级应急预案', value: '园区级应急预案' },
      { label: '企业级应急预案', value: '企业级应急预案' },

    ],
  },
  {
    label: '预案状态：',
    model: 'Review_Status',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '待评审', value: '待评审' },
      { label: '待审批', value: '待审批' },
      { label: '待备案', value: '待备案' },
      { label: '待公布', value: '待公布' },
      { label: '已备案', value: '已备案' },

    ],
  },
])
// 数据相关
const approvafrom = ref({
  Approve_Comment: '',
  Review_Status: ''
})
const reviewnameData = ref([])
const isEditing = ref(false)
const recordData = ref({
  PREPARATION_DEPARTMENT: '',  //编制单位，单位名称
  DEPARTMENT_CODE: '',	//机构代码
  DEPARTMENT_REP: '',	//法定代表人
  DEPARTMENT_REP_PHONE: '',	//法定代表人联系电话
  DEPARTMENT_PER: '',	//公司联系人
  DEPARTMENT_PER_PHONE: '',	//公司联系人联系电话
  DEPARTMENT_FAX: '',	//公司传真
  DEPARTMENT_E_MAIL: '',	//公司电子邮箱
  DEPARTMENT_ADDR: '',	//公司地址
  EMERGENCE_PLAN_NAME: '',	//预案名称

  SUBMIT_DEPARTMENT: '',	//报送单位
  RECORD_DEPART: '',	//备案部门
  RECORD_DEPART_NATURE: '',	//备案部门性质
  RECORD_CODE: '',	//备案编号
  SUBMIT_TIME: '',	//报送时间
  PLAN_TO_RECORD_MATERIAL: '',	//预案备案登记资料
  RECORD_CONTENTS: '',	//突发环境事件应急预案备案目录
  RECORD_COMMENTS: '',	//备案意见
  Review_Status: '已备案',
  files: []
  // EMERGENCE_PLAN_LEVEL	预案等级

})
const planData = ref([])

const jumpToPage = ref(1)
const selectedIds = ref([])
const selectedItem = ref(null)
const isAddDialogOpen = ref(false)
const loading = ref(false)
// 对话框状态
const isImportDialogOpen = ref(false)
const isViewDialogOpen = ref(false)
const isReviewDialogOpen = ref(false)
const fullscreenLoading = ref(false)
const rowKey = (row) => row.ID
// 评审相关数据
const reviewData = ref({
  reviewer_name: '',
  reviewer_code: '',
  reviewer_position: '',
  review_comment: ''
})
const newRecord = ref({
  EMERGENCE_PLAN_ID: '', //预案编码
  PARK_CODE: '', //园区编码
  COMPANY_CODE: '', //企业编码
  AREA_CODE: '', //行政区划
  PREPARATION_DEPARTMENT: '', //编制单位

  EMERGENCE_PLAN_NAME: '', //预案名称
  EMERGENCE_PLAN_TYPE: '', //预案类别
  EMERGENCE_PLAN_LEVEL: '', //预案等级
  RISK_HAS_TOLD_MATERIAL: '', //风险告知周边单位
  files: []
})
const table = ref()


const reservationreviewForm = ref({
  Reviewer_RESULT: "",
  Reviewer_NAME: "",
  Reviewer_TYPE: "",
  Reviewer_STATUS: '',
  Review_Status: ""
})
const isApproval = ref('待评审')

const displayedPlanData = ref([])
const alltabledata = (data) => {
  displayedPlanData.value = data

}
const handleRISK_HAS = (event) => {
  newRecord.value.files[0] = []
  const files = Array.from(event.target.files)
  newRecord.value.files[0] = files[0]

}
const handlePLAN_TO = (event) => {
  recordData.value.files[0] = []
  const files = Array.from(event.target.files)
  recordData.value.files[0] = files[0]

}

const handlePLANFILE = (event) => {
  newRecord.value.files[1] = []
  const files = Array.from(event.target.files)
  newRecord.value.files[1] = files[0]

}
// API 调用函数
const searchPlans = async () => {
  displayedPlanData.value = []
  try {
    const response = await axios.get(`${apiBaseUrl.value}/search`, { params: search.value })
    // console.log('搜索结果:', response.data)
    planData.value = response.data.map(equipment => ({ ...equipment, selected: false }))
    selectedIds.value = []

  } catch (error) {
    console.error('搜索失败:', error)
    alert('搜索失败')
  }
}

const handleSelectionChange = (selected) => {
  selectedIds.value = selected
}
const headerCellStyle = {
  height: '30px', // 设置表头高度
  lineHeight: '30px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
}
const openAddDialog = () => {
  isEditing.value = false
  isAddDialogOpen.value = true
}
const openEditDialog = (item) => {
  item.RISK_HAS_TOLD_YES_OR_NO = String(item.RISK_HAS_TOLD_YES_OR_NO)
  newRecord.value = { ...item }
  newRecord.value.files = []
  isEditing.value = true
  isAddDialogOpen.value = true
}
const closeAddDialog = () => {
  newRecord.value = {}

  isAddDialogOpen.value = false
}

const addNewPlan = async () => {



  if (checkval([
    'EMERGENCE_PLAN_ID',
    'PARK_CODE',
    'COMPANY_CODE',
    'AREA_CODE',
    'EMERGENCE_PLAN_NAME',
    'EMERGENCE_PLAN_TYPE',
    'EMERGENCE_PLAN_LEVEL',
  ], '预案评审', newRecord.value)) {
    return
  }

  if (!newRecord.value.files) {
    alert('预案文件不能为空')
    return
  }


  const formData = new FormData()
  for (const key in newRecord.value) {
    if (key !== 'files') {
      formData.append(key, newRecord.value[key])
    }
  }
  if (newRecord.value?.files) {
    newRecord.value.files.forEach((file, index) => {
      formData.append(`files[${index}]`, file)
    })
  }


  try {


    if (!isEditing.value) {
      const response = await axios.post(apiBaseUrl.value, formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })
      alert('创建评审成功')
    } else {
      const response = await axios.put(apiBaseUrl.value + '/' + newRecord.value.ID, formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })
      alert('编辑评审成功')
    }



    closeAddDialog()
    await searchPlans()
  } catch (error) {
    console.error('创建失败:', error)
    alert('创建失败: ' + (error.response?.data?.message || error.message))
  }
}



const addrecordData = async () => {
  const formData = new FormData()
  for (const key in recordData.value) {
    if (key !== 'files') {
      formData.append(key, recordData.value[key])
    }
  }
  if (recordData.value?.files) {
    recordData.value.files.forEach((file, index) => {
      formData.append(`files[${index}]`, file)
    })
  }

  try {
    const response = await axios.post(`${apiBaseUrl.value}/${selectedItem.value.EMERGENCE_PLAN_ID}/record`, formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    alert('创建预案备案成功')
    closeViewDialog()
    await searchPlans()
  } catch (error) {
    console.error('创建预案备案失败:', error)
    alert('创建预案备案失败: ' + (error.response?.data?.message || error.message))
  }
}

///////////////////////////////////
// 事件处理函数
const resetSearch = () => {
  search.value = {
    EMERGENCE_PLAN_ID: "",
    EMERGENCE_PLAN_TYPE: '',
    EMERGENCE_PLAN_LEVEL: '',
    EMERGENCE_PLAN_NAME: '',
    Review_Status: ''
  }
  searchPlans()
}


const deleteSelected = async () => {
  if (selectedIds.value.length === 0) {
    alert('请选择要删除的记录')
    return
  }
  if (confirm(`确定要删除选中的 ${selectedIds.value.length} 条记录吗？`)) {
    try {
      await Promise.all(selectedIds.value.map(async item => {
        await axios.delete(`${apiBaseUrl.value}/${item.ID}`)
      }
      ))
      alert('删除成功')
      selectedIds.value = []
      table.value.clearSelection()
      await searchPlans()
    } catch (error) {
      console.error('删除记录失败:', error)
      alert('删除记录失败: ' + (error.response?.data?.message || error.message))
    }
  }
}


const viewDetails = (item) => {
  selectedItem.value = { ...item }
  isViewDialogOpen.value = true
}

const closeViewDialog = () => {
  recordData.value = {}
  isViewDialogOpen.value = false

}

const reviewPlan = async (item, name) => {
  selectedItem.value = { ...item }
  if (name != '待评审') {
    try {
      const response = await axios.get(`${apiBaseUrl.value}/${selectedItem.value.ID}/review`, { params: search.value })
      console.log(response)
      reviewnameData.value = response.data.reviewer
    } catch (error) {
      reviewnameData.value = []

    }
  }
  isReviewDialogOpen.value = true
  isApproval.value = name
}

const closeReviewDialog = () => {
  isReviewDialogOpen.value = false
  reservationreviewForm.value = {}
  selectedItem.value = {}
  approvafrom.value = {}
}

const submitReview = async (name) => {

  try {
    if (isApproval.value == '待评审') {
      reservationreviewForm.value.Reviewer_STATUS = name == '待审批' ? '已评审' : '待评审'
      reservationreviewForm.value.Review_Status = name
      const response = await axios.put(`${apiBaseUrl.value}/${selectedItem.value.EMERGENCE_PLAN_ID}/review`,
        reservationreviewForm.value
      )
      alert('评审提交成功')
    } else {
      approvafrom.value.Review_Status = name
      const response = await axios.put(`${apiBaseUrl.value}/${selectedItem.value.ID}/approve`,
        approvafrom.value
      )
      alert('审批提交成功')
    }


    closeReviewDialog()
    await searchPlans()
  } catch (error) {
    console.error('评审提交失败:', error)
    alert('评审提交失败: ' + (error.response?.data?.message || error.message))
  }
}
const subpublish = async (name) => {
  try {
    const response = await axios.put(`${apiBaseUrl.value}/${selectedItem.value.ID}/publish`,
      {

        Review_Status: name
      }
    )
    alert('评审公布成功')
    closeReviewDialog()
    await searchPlans()
  } catch (error) {
    console.error('评审公布失败:', error)
    alert('评审公布失败: ' + (error.response?.data?.message || error.message))
  }

}
// const rejectReview = async () => {
//   try {
//     const response = await axios.put(`${apiBaseUrl.value}/${selectedItem.value.id}/refuse`, {
//       ...reviewData.value,
//       review_status: '驳回'
//     })
//     alert(response.data.message || '评审驳回成功')
//     closeReviewDialog()
//     await searchPlans()
//   } catch (error) {
//     console.error('评审驳回失败:', error)
//     alert('评审驳回失败: ' + (error.response?.data?.message || error.message))
//   }
// }
const importFile = ref(null)

// 打开导入对话框
const openImportDialog = () => {
  isImportDialogOpen.value = true
  console.log('Import dialog opened') // 添加日志
}

// 关闭导入对话框
const closeImportDialog = () => {
  isImportDialogOpen.value = false
  importFile.value = null
  console.log('Import dialog closed') // 添加日志
}



// 文件上传处理
const handleFileUpload = (event) => {
  importFile.value = event.target.files[0]
  console.log('File selected:', importFile.value.name) // 添加日志
}
const confirmImport = async () => {
  if (!importFile.value) {
    alert('请选择要导入的文件')
    return
  }
  const formData = new FormData()
  formData.append('file', importFile.value)
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  try {
    const response = await axios.post(`${apiBaseUrl.value}/import`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    loading.close()
    alert('导入成功')
    closeImportDialog()
    searchPlans()
  } catch (error) {
    loading.close()
    console.error('导入失败:', error)
    alert('导入失败: ' + (error.response?.data?.message || error.message))
  }

}

const textstat = (name) => {
  if (name == '待公布') {
    return 'success'
  } else if (name == '待评审') {
    return 'warning'
  } else if (name == '待审批') {
    return 'danger'
  } else {
    return 'primary'
  }

}



// 生命周期钩子
onMounted(() => {
  searchPlans()
})
</script>

<style scoped>
.input {
  @apply mt-1 block w-full rounded-md border-input bg-background px-3 py-2 text-sm shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50;
}

.select {
  @apply mt-1 block w-full rounded-md border-input bg-background px-3 py-2 text-sm shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50;
}

.btn {
  @apply px-4 py-2 rounded-md font-medium focus:outline-none focus:ring-2 focus:ring-offset-2 transition duration-150 ease-in-out;
}

.btn-sm {
  @apply px-2 py-1 text-sm;
}

.btn-primary {
  @apply bg-primary text-primary-foreground hover:bg-primary/90;
}

.btn-secondary {
  @apply bg-secondary text-secondary-foreground hover:bg-secondary/80;
}

.btn-destructive {
  @apply bg-destructive text-destructive-foreground hover:bg-destructive/90;
}

.btn-warning {
  @apply bg-warning text-warning-foreground hover:bg-warning/90;
}

.checkbox {
  @apply h-4 w-4 text-primary focus:ring-primary border-input rounded;
}
</style>
